<template>
  <div class="confirm-order">
    <div class="confirm-order-head">
      <cp-nav-bar title="确认订单" onClickLeft />
    </div>
    <div class="confirm-order-body">
      <div class="body-top">
        <p class="name">{{ scenic?.scenicName }} - {{ pricelist.ticketName }}</p>
        <p class="selectData"
          v-if="route.query.ticketType !== '4' && route.query.ticketType !== '5' && route.query.ticketType !== '6'">
          选择日期：{{
            selectDate }}</p>
        <div class="dataCard"
          v-if="route.query.ticketType !== '4' && route.query.ticketType !== '5' && route.query.ticketType !== '6'">
          <span @click="selectthreeday(todayFormatted, threeDayPrice?.todayprice, 0)"
            :class="{ highlight: selectedDate === 0 }">
            <p>今天{{ todayFormatted }}</p>
            <p>￥{{ threeDayPrice?.todayprice }}</p>
          </span>
          <span @click="selectthreeday(tomorrowFormatted, threeDayPrice?.tomorrowprice, 1)"
            :class="{ highlight: selectedDate === 1 }">
            <p>明天{{ tomorrowFormatted }}</p>
            <p>￥{{ threeDayPrice?.tomorrowprice }}</p>
          </span>
          <span @click="selectthreeday(afterTomorrowFormatted, threeDayPrice?.afterTomorrowprice, 2)"
            :class="{ highlight: selectedDate === 2 }">
            <p>后天{{ afterTomorrowFormatted }}</p>
            <p>￥{{ threeDayPrice?.afterTomorrowprice }}</p>
          </span>

          <span @click="getMoreDate" :class="{ highlight: selectedDate === 3 }">
            <i>更多日期</i><i>></i>
          </span>
        </div>
        <p style="display: flex;justify-content: space-between; margin-top: 10px">
          <span style="color: #028ef2;">景区官网 无需取票 未用可退</span>
          <span style="color: #a9aaad;" @click="getNotice">购买须知></span>
        </p>
      </div>
      <div class="selectTourist">
        <p class="title">需填写1位游客</p>
        <div class="touristInfo">
          <span class="touristInfo-title">游&nbsp;&nbsp;&nbsp;客</span>
          <van-form ref="formRef" :key="formKey">
            <van-cell-group inset>
              <van-field v-model="form.touristName" name="姓名" label="" placeholder="填写姓名"
                :rules="[{ required: true, message: '请填写用户名' }]" />
              <van-field v-model="form.touristIdCard" name="身份证" label="" placeholder="请填写身份证"
                :rules="[{ validator: () => idCardNoUtil.checkIdCardNo(form.touristIdCard), message: '身份证号不正确' }]" />
              <van-field v-model="form.touristPhone" name="手机号" label="" placeholder="请填写手机号" :rules="mobileRules" />
            </van-cell-group>
          </van-form>
          <!-- </span> -->
          <span style="color: #c4c4c4;">
            <!-- <van-icon @click="edit" name="edit" style="margin-right:10px;" /> -->
            <van-icon name="clear" @click="clear" />
          </span>
        </div>
      </div>
      <div class="couponSelection">
        <span>平台优惠</span>
        <span @click="selectCoupon">{{ selectvoucherAmount ? `-￥${selectvoucherAmount}` : "请选择 > " }}</span>
      </div>
      <div class="telephone">
        <span>手机号码</span>
        <span>{{ userPhone }}</span>
      </div>


    </div>
    <div class="confirm-order-foot">
      <div class="footInfo" @click="getPriceDetail">
        <p><i v-if="selectDatePrice">￥</i><span class="price" v-if="selectDatePrice">{{ selectvoucherAmount ?
          (selectDatePrice * 100 -
            selectvoucherAmount * 100) / 100 : selectDatePrice }}</span> <span class="firstPrice"
            v-if="selectvoucherAmount"><i>￥</i>{{
              selectDatePrice }}</span></p>
        <p v-if="selectvoucherAmount" style="color: var(--cp-primary);margin-top:2px;">优惠{{ selectvoucherAmount }}元
          <span style="color:rgba(166, 166, 166, 1);margin-right: 10px;">明细</span><van-icon name="play"
            style="transform: rotate(-90deg);color:rgba(166, 166, 166, 1) " />
        </p>
      </div>
      <div>
        <van-button class="confirmbtn" type="primary" @click="submitForm">提交订单</van-button>
      </div>
    </div>
    <!-- 选择优惠券的弹框 -->
    <van-popup v-model:show="showCoupon" round position="bottom" closeable close-icon-position="top-left"
      :style="{ height: '40%' }" class="popupBg">
      <p class="popupTitle">平台优惠</p>
      <div class="couponCard" v-for="item in couponList" :key="item.id" @click="chooseCoupon(item)">
        <span>￥{{ item.voucherAmount }}</span>
        <span>
          <p>{{ item.voucherName }}</p>
          <p>有效期</p>
          <p>{{ item.effectiveTime }}</p>
        </span>
        <span>
          <img :src="item.checked ? select : unselects" alt="">
        </span>
      </div>
    </van-popup>
    <!-- 查看优惠明细的弹框 -->
    <van-popup v-model:show="show" round position="bottom" closeable close-icon-position="top-left"
      :style="{ height: '30%' }" class="popupBg">
      <p class="popupTitle">费用明细</p>
      <div class="popupContent" v-if="selectCouponList.voucherName">
        <span>{{ selectCouponList.voucherName }}优惠券</span>
        <span> -￥{{ selectCouponList.voucherAmount }}</span>
      </div>
    </van-popup>

    <!-- 日历组件 -->
    <van-calendar v-model:show="showCalendar" :value="currentDate" switch-mode="month" :min-date="minDate"
      :max-date="maxDate" :formatter="formatter" @confirm="getSelectDate" />
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, onMounted, watch, getCurrentInstance } from 'vue'
import { getUserInfo } from '@/services/user'
import { idCardRules, mobileRules } from '@/utils/rules'
import { idCardNoUtil } from '@/utils/idCardUtil.js'
import { getPhList, getTicketList, getScenicById, getpreOrder, getVoucherList } from '@/services/home'
import { useRoute, useRouter } from 'vue-router'
import { showDialog, showToast } from 'vant';
import select from '@/assets/activity/icon_cg.png'
import unselects from '@/assets/activity/icon_cg_02.png'
const formKey = ref(0);
const route = useRoute()
const router = useRouter()
const show = ref(false)
const showCoupon = ref(false)
const showCalendar = ref(false)
const currentDate = new Date()
const minDate = new Date()
minDate.setHours(0, 0, 0, 0); // 设置时间为当天的开始时间（午夜）
const maxDate = new Date()
maxDate.setDate(maxDate.getDate() + 60); // 设置时间为当天的日期加上60天
const pricelist = ref({}) //各种票类型的价格
const threeDayPrice = ref({}) //今明后三天的列表
const PhList = ref([]) //节假日列表
const scenic = ref()
const form = ref({})
const formRef = ref(null)
const userPhone = ref()
const selectDate = ref()
const selectDatePrice = ref()
const selectvoucherAmount = ref()
const couponList = ref([]) //领取的优惠券
const selectCouponList = ref([]) //领取的优惠券
const showPicker = ref(false) //选择优惠券框
const checked = ref(false) //是否选择此优惠券
const voucherId = ref() //是否选择此优惠券
const selectedDate = ref() //选择的按钮

// const getidCardRules = () => {
//   return [
//     // { required: true, message: '请输入拜访用户数量' },
//     // { pattern: /^[1-9]\d*$/, message: '请输入正整数' },
//     // {
//     validator: idCardNoUtil.checkIdCardNo,
//     message: '身份证号格式不正确'
//     // }
//   ]

// }
// 今天明天后天的年月日转换
function getFormattedDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的
  const day = String(date.getDate()).padStart(2, '0');
  return `${month}-${day}`;
}

// 获取今天的日期
const today = new Date();
const todayFormatted = getFormattedDate(today);

// 获取明天的日期
const tomorrow = new Date(today);
tomorrow.setDate(tomorrow.getDate() + 1);
const tomorrowFormatted = getFormattedDate(tomorrow);

// 获取后天的日期
const afterTomorrow = new Date(today);
afterTomorrow.setDate(afterTomorrow.getDate() + 2);
const afterTomorrowFormatted = getFormattedDate(afterTomorrow);

// 日历上的价格回显
const formatter = (day: any) => {
  const Cmonth = day.date.getMonth() + 1;
  const Cdate = day.date.getDate();
  if (pricelist.value.ticketType == '0' || pricelist.value.ticketType == '1' || pricelist.value.ticketType == '2') {
    day.bottomInfo = `￥${pricelist.value.weekdayPrice}`;
    // 遍历objects数组
    for (let i = 0; i < PhList.value.length; i++) {
      const objDate = new Date(PhList.value[i].phDate);
      const month = objDate.getMonth() + 1;
      const date = objDate.getDate();
      // 比较月份和日期
      if (month === Cmonth && date === Cdate) {
        // 如果找到匹配的日期，设置day.bottomInfo为"节假日"
        day.bottomInfo = `￥${pricelist.value.phPrice}`;
      }
    }
  } else {
    day.bottomInfo = `￥${pricelist.value.discountPrice}`;
  }
  return day;
};
// 打开优惠券的弹框
const selectCoupon = () => {
  showCoupon.value = !showCoupon.value
  getVoucherList({ voucherStatus: 0, scenicId: route.query.scenicId }).then((e) => {
    if (e.code === 200) {
      couponList.value = e.rows
      couponList.value.forEach(item => {
        item.checked = false
        if (item.voucherId == selectCouponList.value.voucherId) {
          item.checked = true
        }
      })
      // selectCouponList.value[0].voucherId

      console.log('转换后的接口：', couponList.value);

      showPicker.value = true
    }
  })
}
// 点击选择优惠券后关闭弹框
const chooseCoupon = (item) => {
  // console.log('选中的数组：：', item);

  if (!selectDatePrice.value) {
    return showToast('请选择日期')
  } else if (selectDatePrice.value <= item.voucherAmount) {
    return showToast('优惠券金额不能大于订单金额')
  }
  // couponList.value.forEach(e => {
  //   e.checked = false
  // })
  // console.log('点击前：：', item.checked);

  item.checked = !item.checked
  if (!item.checked) {
    selectvoucherAmount.value = 0
    voucherId.value = ''
    selectCouponList.value = {}
    // console.log('改变了么？', selectvoucherAmount.value);

  } else {
    selectvoucherAmount.value = item.voucherAmount
    voucherId.value = item.id
    selectCouponList.value = item
  }
  // 打开优惠前详情展示的数据
  // console.log('selectCouponList.value:', selectCouponList.value);
  // console.log('couponList.value:', couponList.value);
  // console.log('点击的：', item.voucherId);

  // if (voucherId.value && voucherId.value !== item.voucherId) {
  //   // if (selectCouponList.value.length > 1) {
  //   return showToast('只能选择一张优惠券')
  // }
  // selectCouponList.value = couponList.value.filter((item) => item.checked)
  showCoupon.value = !showCoupon.value
  // console.log('选中的优惠券：', selectCouponList.value);
  console.log('选中的ID：：', voucherId.value);
}

const getPriceDetail = () => {
  console.log('拉起支付');
  show.value = !show.value
  // getVoucherList({voucherStatus:0,scenicId:route.query.scenicId}).then((e) => {
  //     if(e.code === 200){
  //       couponList.value = e.rows
  //       showPicker.value = true
  //     }
  //   })
}
const clear = () => {
  form.value = {
    touristName: '',
    touristPhone: '',
    touristIdCard: '',
  }
  formKey.value++;
}
const getSelectDate = (value) => {
  showCalendar.value = false
  const selectMonth = String(value.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的
  const selectDay = String(value.getDate()).padStart(2, '0');
  selectDate.value = `${selectMonth}-${selectDay}`
  console.log('四个日期：', selectDate.value, todayFormatted, tomorrowFormatted, afterTomorrowFormatted);

  if (selectDate.value !== todayFormatted && selectDate.value !== tomorrowFormatted && selectDate.value !== afterTomorrowFormatted) {
    selectedDate.value = 3
  } else if (selectDate.value === todayFormatted) {
    selectedDate.value = 0
  } else if (selectDate.value === tomorrowFormatted) {
    selectedDate.value = 1
  } else if (selectDate.value === afterTomorrowFormatted) {
    selectedDate.value = 2
  }
}

const selectthreeday = (value1, value2, num) => {
  selectDate.value = value1
  selectedDate.value = num
  selectDatePrice.value = value2
}
// 提交订单的按钮
const submitForm = () => {
  if (selectDate.value === undefined && (route.query.ticketType !== '4' && route.query.ticketType !== '5' && route.query.ticketType !== '6')) {
    showDialog({ message: "请选择日期" })
  }
  if (selectDate.value) {
    formRef.value.validate().then(() => {
      // 如果验证通过，调用onSubmit
      getpreOrder({
        scenicFlag: route.query.scenicFlag,
        ticketId: route.query.id,
        scenicId: route.query.scenicId,
        voucherDetailId: voucherId.value,
        ticketDate: new Date().getFullYear() + '-' + selectDate.value,
        userTicketList: [{ ...form.value }]
      }).then(res => {
        if (res.code === 200) {
          console.log('预下单接口:', res.data);
          router.push({
            path: '/orderPay',
            query: { ...res.data }
          })
        }
      })
    })
  } else if (selectDate.value === undefined && (route.query.ticketType == '4' || route.query.ticketType == '5' || route.query.ticketType == '6')) {
    // 这个地方进入的是月卡、年卡、季卡
    formRef.value.validate().then(() => {
      // 如果验证通过，调用onSubmit
      getpreOrder({
        scenicFlag: route.query.scenicFlag,
        ticketId: route.query.id,
        scenicId: route.query.scenicId,
        voucherDetailId: voucherId.value,
        userTicketList: [{ ...form.value }]
      }).then(res => {
        if (res.code === 200) {
          console.log('预下单接口:', res.data);
          router.push({
            path: '/orderPay',
            query: { ...res.data }
          })
        }
      })
    })
  }
}

const getNotice = () => {
  showDialog({ message: pricelist.value.remark, showConfirmButton: false, closeOnClickOverlay: true })
}
const getMoreDate = () => {
  showCalendar.value = !showCalendar.value
}
// 价格信息对应门票设置接口
const getTicketPrice = () => {
  getTicketList({ id: route.query.id }).then(res => {
    pricelist.value = res.rows[0]
    if (route.query.ticketType == '4' || route.query.ticketType == '5' || route.query.ticketType == '6') {
      selectDatePrice.value = pricelist.value.discountPrice
    }
    getPhList({ "dateType": 0 }).then((e) => {
      PhList.value = e.rows
      console.log('节日接口：', pricelist.value.weekdayPrice);
      if (e.rows.some(obj => obj.phDate.slice(5, 10) === todayFormatted)) {
        threeDayPrice.value.todayprice = pricelist.value.ticketType == '0' || pricelist.value.ticketType == '1' || pricelist.value.ticketType == '2' ? pricelist.value.phPrice : pricelist.value.discountPrice
      } else {
        threeDayPrice.value.todayprice = pricelist.value.ticketType == '0' || pricelist.value.ticketType == '1' || pricelist.value.ticketType == '2' ? pricelist.value.weekdayPrice : pricelist.value.discountPrice
      }
      if (e.rows.some(obj => obj.phDate.slice(5, 10) === tomorrowFormatted)) {
        threeDayPrice.value.tomorrowprice = pricelist.value.ticketType == '0' || pricelist.value.ticketType == '1' || pricelist.value.ticketType == '2' ? pricelist.value.phPrice : pricelist.value.discountPrice
      } else {
        threeDayPrice.value.tomorrowprice = pricelist.value.ticketType == '0' || pricelist.value.ticketType == '1' || pricelist.value.ticketType == '2' ? pricelist.value.weekdayPrice : pricelist.value.discountPrice
      }
      if (e.rows.some(obj => obj.phDate.slice(5, 10) === afterTomorrowFormatted)) {
        console.log('是');
        threeDayPrice.value.afterTomorrowprice = pricelist.value.ticketType == '0' || pricelist.value.ticketType == '1' || pricelist.value.ticketType == '2' ? pricelist.value.phPrice : pricelist.value.discountPrice
      } else {
        console.log('不是');
        threeDayPrice.value.afterTomorrowprice = pricelist.value.ticketType == '0' || pricelist.value.ticketType == '1' || pricelist.value.ticketType == '2' ? pricelist.value.weekdayPrice : pricelist.value.discountPrice
      }
    })
  })
}

const getDetail = () => {
  getScenicById(route.query.scenicId).then(res => {
    console.log('景区详情：', res);
    scenic.value = res.data
  })
}
const getUserPhone = () => {
  getUserInfo().then(res => {
    userPhone.value = res.data.phone
  })
}
onMounted(() => {
  getTicketPrice()
  getDetail()
  getUserPhone()
})
</script>
<style scoped lang="scss">
.confirm-order {
  width: 375px;
  min-height: calc(100vh - 50px);
  padding-top: 50px;
  background-color: var(--cp-bg);
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-direction: column;

  .confirm-order-body {
    flex: 1;

    .body-top {
      padding: 10px;
      width: 350px;
      //height: 158px;
      background-color: #fff;
      margin-top: 10px;
      margin-bottom: 15px;

      .name {
        font-size: 18px;
        font-weight: 900;
      }

      .selectData {
        font-size: 16px;
        font-weight: 700;
        margin-top: 10px;
      }

      .dataCard {
        margin-top: 10px;
        display: flex;
        justify-content: space-between;

        span {
          display: inline-block;
          width: 80px;
          height: 40px;
          background-color: #f0f0f0;
          border-radius: 2px;
          padding: 5px;

          & p:nth-child(1) {
            font-size: 13px;
            font-weight: 500;
          }

          & p:nth-child(2) {
            padding-top: 5px;
            font-size: 13px;
            color: rgba(203, 22, 29, 1);
          }
        }

        & span:nth-child(4) {
          width: 40px;
          display: flex;
          align-items: center;

          i {
            font-style: normal;
            font-size: 13px;
          }
        }
      }
    }

    .selectTourist {
      background-color: #fff;
      width: 350px;
      // height: 140px;
      margin-bottom: 15px;
      padding: 10px;

      .title {
        font-size: 14px;
        margin-bottom: 7px;
      }

      .name {
        span {
          padding: 5px;
          border-radius: 2px;
          background-color: #f7dedf;
          border: 0.5px solid rgba(198, 20, 27, 1);
          ;
        }
      }

      .touristInfo {
        display: flex;
        align-items: center;
        justify-content: space-around;
        margin-top: 10px;

        .touristInfo-title {
          margin-left: 20px;
          font-size: 15px;
          font-weight: 600;
        }
      }


    }

    .couponSelection {
      margin-bottom: 15px;
      padding: 10px;
      background-color: #fff;
      width: 350px;
      height: 40px;
      line-height: 40px;

      span:nth-child(1) {
        margin-right: 20px;
      }

      span:nth-child(2) {
        float: right;
      }
    }

    .telephone {
      margin-bottom: 15px;
      padding: 10px;
      background-color: #fff;
      width: 350px;
      height: 40px;
      line-height: 40px;

      span {
        margin-right: 20px;
      }

    }
  }

  .confirm-order-foot {
    width: 100%;
    height: 60px;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-around;

    .footInfo {
      font-size: 10px;
      width: 100px;
      color: rgba(166, 166, 166, 1);

      i {
        font-style: normal;
        color: rgba(198, 20, 27, 1)
      }

      .price {
        font-size: 14px;
        color: rgba(198, 20, 27, 1);
        font-weight: 700;
      }

      .firstPrice {
        text-decoration: line-through;

        i {
          color: rgba(166, 166, 166, 1);
        }
      }
    }

    .confirmbtn {
      display: block;
      width: 225px;
      height: 44px;
      border-radius: 22px;
      background-color: rgba(198, 20, 27, 1);
      color: #fff;
      text-align: center;
      line-height: 44px;
    }
  }

  .popupBg {
    background-color: var(--cp-bg);

    .popupTitle {
      background-color: #fff;
      font-size: 18px;
      text-align: center;
      font-weight: 400;
      line-height: 50px;
      color: rgba(29, 33, 41, 1);
    }

    // 优惠的样式
    .popupContent {
      height: 50px;
      padding: 0 10px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      & span:nth-child(2) {
        color: red;
      }
    }

    // 优惠券的样式
    .couponCard {
      display: flex;
      align-items: center;
      // justify-content: space-around;
      width: 343px;
      height: 92px;
      margin: auto;
      background: url(@/assets/activity/bg.png) no-repeat;
      background-size: cover;
      margin-top: 10px;

      & span:nth-child(1) {
        margin-left: 25px;
        width: 40px;
        color: #f65332;
        font-size: 16px;
        font-weight: 600;
      }

      & span:nth-child(2) {
        margin-left: 40px;
        width: 140px;
        text-align: center;
        color: #A3AEB6;
        font-size: 12px;

        & p:nth-child(1) {
          color: #000;
          font-size: 14px;
          text-overflow: ellipsis;
          overflow: hidden;
          white-space: nowrap;
        }
      }

      & span:nth-child(3) {
        margin-left: 50px;

        img {
          width: 16px;
          height: 16px;
        }
      }

    }
  }

  .highlight {
    background-color: rgba(198, 20, 27, 1) !important;
    color: #fff !important;

    & p:nth-child(2) {
      color: #fff !important;
    }
  }
}

:deep(.van-field__error-message) {
  position: absolute !important;
  bottom: -18px;
}

:deep(.van-field) {
  padding-top: 5px !important;
}
</style>
